package cn.qingyun.gis.modules.scenes.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.qingyun.gis.exception.CommonException;
import cn.qingyun.gis.minio.util.MinioTool;
import cn.qingyun.gis.modules.scenes.contant.TypeStatus;
import cn.qingyun.gis.modules.scenes.entity.PoiScenarioAppendix;
import cn.qingyun.gis.modules.scenes.mapper.PoiScenarioAppendixMapper;
import cn.qingyun.gis.modules.scenes.request.AudioRequest;
import cn.qingyun.gis.modules.scenes.response.SpeechTextGetResponse;
import cn.qingyun.gis.modules.scenes.service.IPoiScenarioAppendixService;
import cn.qingyun.gis.modules.scenes.util.BaseUtil;
import cn.qingyun.gis.modules.scenes.util.FilePathToFileUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author guest
 * @since 2024-04-28
 */
@Slf4j
@Service
@DS("scenes_offensive")
public class PoiScenarioAppendixServiceImpl extends ServiceImpl<PoiScenarioAppendixMapper, PoiScenarioAppendix> implements IPoiScenarioAppendixService {

    @Value("${qingyun.speech.convert-word-url}")
    private String CONVERT_WORD_URL;

    /**
     * 语音转文字并入库
     *
     * @param file      语音文件
     * @param id        主键
     * @param type
     * @param startTime 开始时间
     * @param endTime   结束时间
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SpeechTextGetResponse getSpeechText(MultipartFile file, String id, String type, Date startTime, Date endTime){
        SpeechTextGetResponse speechTextGetResponse = new SpeechTextGetResponse();
        try {
            // 录音文件 上传到minio
            String uploadMp3 = MinioTool.upload(file);
            PoiScenarioAppendix speechFile = PoiScenarioAppendix.builder()
                    .poiScenarioId(id)
                    .minioPath(uploadMp3)
                    .type(TypeStatus.AUDIO.getDesc())
                    .startTime(startTime)
                    .endTime(endTime)
                    .createTime(DateUtil.date())
                    .build();
            this.save(speechFile);

            // 文本识别
            InputStream inputStream = file.getInputStream();
            HttpResponse response = HttpUtil.createPost(CONVERT_WORD_URL).
                    form("file", inputStream)
                    .timeout(1000)
                    .execute();
            if (response.isOk()) {
                JSONObject parseObj = JSONUtil.parseObj(response.body());
                String data = (String) parseObj.getByPath("data");
                if (StringUtils.isNotBlank(data)) {
                    String fileName = id + ".txt";
                    String filePath = BaseUtil.getUploadFilesPath() + "/" + fileName;
                    BufferedWriter writer = null;
                    try {
                        writer = new BufferedWriter(new FileWriter(filePath));
                        writer.write(data);
                        writer.close();
                        MultipartFile multipartFile = FilePathToFileUtil.filePathToFileItem(filePath);
                        String uploadTxt = MinioTool.upload(multipartFile);
                        //保存至数据库
                        PoiScenarioAppendix txtFile = PoiScenarioAppendix.builder()
                                .poiScenarioId(id)
                                .minioPath(uploadTxt)
                                .type(TypeStatus.TEXT.getDesc())
                                .startTime(startTime)
                                .endTime(endTime)
                                .createTime(DateUtil.date())
                                .build();
                        this.save(txtFile);
                        speechTextGetResponse.setMp3Path(uploadMp3);
                        speechTextGetResponse.setTxtPath(uploadTxt);
                    } finally {
                        if (new File(filePath).exists()) {
                            new File(filePath).delete();
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new CommonException("语音转文字失败：", e);
        }
        return speechTextGetResponse;
    }

    /**
     * 保存录音记录
     * @param request
     */
    @Override
    public void saveAppendixRecord(AudioRequest request) {
        log.debug("保存录音文件记录入参{}",request);
        String relationId = IdUtil.getSnowflake(1, 1).nextIdStr();
        PoiScenarioAppendix txtFile = PoiScenarioAppendix.builder()
                .proofreadId(request.getChainId())
                .minioPath(request.getMp3Path())
                .relationId(relationId)
                .timeSlot(request.getTimeSlot())
                .type(TypeStatus.AUDIO.getDesc())
                .startTime(request.getStartTime())
                .endTime(request.getEndTime())
                .createTime(DateUtil.date())
                .build();
        this.save(txtFile);
        log.debug("录音记录保存成功！");
    }
}
